package com.restkeeper.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.restkeeper.gateway.config.customCode.dic.CodeConstants;
import com.restkeeper.gateway.config.customCode.handler.CustomCodeHandler;
import com.restkeeper.utils.JWTUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RefreshScope
public class AuthFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);
    @Value("#{'${gateway.excludedUrls}'.split(',')}")
    private List<String> excludedUrls;

    @Value("${gateway.secret}")
    private String secret;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Map<String, CustomCodeHandler> handleMap;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取当前请求路径
        String path = exchange.getRequest().getURI().getPath();
        //排除特殊不需要令牌的路径
        if (excludedUrls.contains(path)){
            return chain.filter(exchange);
        }
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //获取令牌信息
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StringUtils.isNotEmpty(token)){
            //获取登录状态
            String userId = (String) redisTemplate.opsForValue().get(token);
            log.info("*******************************userId****************[{}]",userId);
            if (StringUtils.isBlank(userId)){
                Map<String,Object> responseData = Maps.newHashMap();
                responseData.put("code","5001");
                responseData.put("message","登录状态过期");
                return responseError(response,responseData,HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
            }
            JSONObject userState = JSONObject.parseObject((String) redisTemplate.opsForValue().get(userId));
            log.info("*******************************userState****************[{}]",userState);
            if(userState==null){
                Map<String,Object> responseData = Maps.newHashMap();
                responseData.put("code","5001");
                responseData.put("message","登录状态过期");
                return responseError(response,responseData,HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
            }
            String accountState=userState.getString("accountState");
            String loginState=userState.getString("loginState");
            if("ban".equals(accountState)){
                log.info("*******************************ban****************[{}]",accountState);
                //令牌校验不通过
                Map<String,Object> responseData = Maps.newHashMap();
                responseData.put("code","5001");
                responseData.put("message","账号已禁用");
                return responseError(response,responseData,HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
            }
            if("cancel".equals(accountState)){
                log.info("*******************************ban****************[{}]",accountState);
                //令牌校验不通过
                Map<String,Object> responseData = Maps.newHashMap();
                responseData.put("code","5001");
                responseData.put("message","账号已注销");
                return responseError(response,responseData,HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
            }
            if("out".equals(loginState)){
                log.info("*******************************out****************[{}]",loginState);
                //令牌校验不通过
                Map<String,Object> responseData = Maps.newHashMap();
                responseData.put("code","5001");
                responseData.put("message","账号已退出登录");
                return responseError(response,responseData,HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
            }
            //合法性进行判断
            JWTUtil.VerifyResult verifyResult = JWTUtil.verifyJwt(token, secret);
            if (verifyResult.isValidate()){
                //令牌校验通过
                return chain.filter(exchange);
            }else{
                //令牌校验不通过
                Map<String,Object> responseData = Maps.newHashMap();
                responseData.put("code",verifyResult.getCode());
                responseData.put("message","验证失败");
                return responseError(response,responseData,HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
            }
        }else{
            //令牌不存在
            //返回错误信息
            Map<String,Object> responseData = Maps.newHashMap();
            responseData.put("code",401);
            responseData.put("message","非法请求");
            responseData.put("cause","token is empty");
            return responseError(response,responseData,HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
        }
    }

    //返回响应数据
    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData) {
        //将信息转换为json
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try{
            data = objectMapper.writeValueAsBytes(responseData);
        }catch (Exception e){
            e.printStackTrace();
        }

        //输出结果数据
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");
        return response.writeWith(Mono.just(buffer));
    }

    //返回响应数据
    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData,HttpStatus status) {

        //将信息转换为json
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try{
            data = objectMapper.writeValueAsBytes(responseData);
        }catch (Exception e){
            e.printStackTrace();
        }

        //输出结果数据
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(status);
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }



}
